package com.gzc.just.play.last.war.common.message.handler;

import com.gzc.just.play.last.war.common.service.MessageService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Chat message handler
 */
@Component
public class ChatMessageHandler implements MessageHandlerInterface {

    private static final Logger log = LoggerFactory.getLogger(ChatMessageHandler.class);

    private final MessageService messageService;
    private final ObjectMapper objectMapper;
    
    public ChatMessageHandler(MessageService messageService, ObjectMapper objectMapper) {
        this.messageService = messageService;
        this.objectMapper = objectMapper;
    }

    @Override
    public void handle(Long playerId, Object messageData) {
        try {
            // Parse chat data
            Map<String, Object> chatData = objectMapper.convertValue(messageData, Map.class);
            
            String content = (String) chatData.get("content");
            String channel = (String) chatData.getOrDefault("channel", "world");
            Long targetId = chatData.containsKey("targetId") ? 
                Long.valueOf(chatData.get("targetId").toString()) : null;
            
            // Filter sensitive words and validate message
            if (!validateChatMessage(content)) {
                log.warn("Invalid chat message from player {}: {}", playerId, content);
                return;
            }
            
            // Process chat message - corrected parameter order
            messageService.sendChatMessage(playerId, targetId, content, channel);
            
            log.debug("Player {} sent chat message in channel {}: {}", playerId, channel, content);
        } catch (Exception e) {
            log.error("Error processing chat message for player: {}", playerId, e);
        }
    }
    
    /**
     * Validate chat message
     */
    private boolean validateChatMessage(String content) {
        // Check message length
        if (content == null || content.isEmpty() || content.length() > 200) {
            return false;
        }
        
        // Check sensitive words
        if (containsSensitiveWords(content)) {
            return false;
        }
        
        return true;
    }
    
    /**
     * Check for sensitive words
     */
    private boolean containsSensitiveWords(String content) {
        // Sensitive word filtering logic can be implemented here
        // Simplified implementation, actual projects should use a more complete sensitive word library
        String[] sensitiveWords = {"badword1", "badword2"};
        
        for (String word : sensitiveWords) {
            if (content.contains(word)) {
                return true;
            }
        }
        
        return false;
    }
}
